package com.colud.client.handler;

import com.colud.client.util.JT809Constants;
import com.colud.client.vo.Message;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 心跳处理机制
 */
public class HeartBeatHandler extends IdleStateAwareChannelHandler {

    private static Logger log = LoggerFactory.getLogger(HeartBeatHandler.class);

    @Override
    public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {

        if (e.getState() == IdleState.WRITER_IDLE) {
            log.info("链路空闲，发送心跳!");
            Message msg = new Message(JT809Constants.UP_LINKTEST_REQ);
            ChannelBuffer channelBuffer = ChannelBuffers.buffer(0);
            msg.setMsgBody(channelBuffer);
            e.getChannel().write(msg);
            super.channelIdle(ctx, e);
        }
    }

}
